/**
 * Created by WLG on 2018/11/9.
 */
let ChatBusinessService = require("../services/chatBusinessService");
let ChatMemInfoService = require("../services/chatMemInfoService");
let ChatMsgService = require("../services/chatMsgService");
let ServerConfig = require('../config/serverConfig');
let ObsManager = require('../lib/obsManager');
let Router = require('koa-router');
let fs = require('fs');
let uuid = require('uuid');



class FileMangerHandler {
    static attach(app,io){
        let router = new Router();
        router
            .post([ServerConfig.httpNameSpace,"uploadFile"].join("/") , async (ctx, next) => {
                const file = ctx.request.files.file; // 获取上传文件
                // 创建可读流
                let fileName = file.name;
                let fileType = fileName.substr(fileName.lastIndexOf("."));
                const reader = fs.createReadStream(file.path+"");
                let bucketName = ServerConfig.obsConfig.bucketName;
                let fileKey = uuid.v1() + fileType;
                let ContentDisposition = "attachment;filename* = UTF-8''"+encodeURI(fileName, "utf-8");
                let result = await ObsManager.getClient().putObject({
                    Bucket : bucketName,
                    Key : fileKey,
                    // 创建文件流
                    Body : reader,
                    //测试 通过 ContentDisposition 配置文件名 目前不起作用
                    ContentDisposition : ContentDisposition,
                    'Content-Disposition' : ContentDisposition,
                    Metadata : {'ContentDisposition':ContentDisposition,'Content-Disposition':ContentDisposition}
                }).catch(function(e){
                    logError.error('obs error', e )
                });
                await next();
            });
        app.use(router.routes()).use(router.allowedMethods());
    };
}
module["exports"] = FileMangerHandler;